# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pandas as pd
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class StandardPipeline:
    def process_item(self, item, spider):
        return item

class HouseExcelPipeLine:
    def open_spider(self, spider):
        """
        初始化
        """
        if spider.name == 'house':
            # 创建一个writer文件写入对象 数据写入文件
            self.writer = pd.ExcelWriter('houses.xlsx')
            self.data = []

    def process_item(self, item, spider):
        """
        数据处理  将豆瓣数据对象存入到self.data中
        :param item:豆瓣数据对象
        :return:
        """
        if spider.name == 'house':
            self.data.append({
                '板块': item['type'],
                '标题': item['title'],
                '面积': item['area'],
                '朝向': item['direction_desc'],
                '装修类型': item['fitment_name'],
                '楼盘': item['resblock_name'],
                '月租金': item['sell_price'],
                '单位平米租金': item['unit_month_rent_price'],
                '经纬度': item['geo'],
            })
        return item

    def close_spider(self,spider):
        """
        爬虫结束后将数据写入到Excel文件中 并且关闭文件
        :return:
        """
        if spider.name == 'house':
            df = pd.DataFrame(self.data)
            df.to_excel(self.writer, index=False)
            self.writer.close()

    # def close_spider(self, spider):
    #     if spider.name == 'house':
    #         df = pd.DataFrame(self.data)
    #         df.to_excel(self.writer, index=False)
    #         self.writer.close()

